<template>
  <div>
    <vue-ueditor-wrap v-model="content" :config="myConfig" @beforeInit="addCustomButtom"></vue-ueditor-wrap>
    <a-modal
      title="图片上传"
      :visible.sync="dialogVisible"
      width="60%"
      :lock-scroll="true"
      :close-on-click-modal="false"
      @cancel="cancel"
    >
      <div class="image-upload-panel">
        <a-upload
          listType="picture-card"
          :fileList="fileList"
          :beforeUpload="beforeUpload"
          @change="handleChange"
        >
          <div v-if="fileList.length < 8">
            <a-icon type="plus" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <a-button @click="()=>{this.dialogVisible=false}">取 消</a-button>
        <a-button type="primary" @click="insertImage" :loading="!uploadING">确 定</a-button>
      </span>
    </a-modal>
  </div>
</template>

<script>
import VueUeditorWrap from 'vue-ueditor-wrap'
import { uploadPic } from '@/api/login'
let loading
export default {
  components: {
    VueUeditorWrap
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    myConfig: {
      type: Object,
      default: () => ({
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 400,
        // 初始容器宽度
        initialFrameWidth: 800,
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: '/static/plugin/UEditor/'
      })
    }
  },
  data() {
    return {
      loading: undefined,
      api: {
        /**
         * 图片上传地址
         */
        uploadImage: '/api/imageUpload'
      },
      dialogVisible: false,
      imageList: [],
      editorHandler: null,
      content: this.value,
      fileList: [],
      uploadING: false
    }
  },
  methods: {
    //删除图片
    delImage(index) {
      let imageList = this.imageList
      imageList.splice(index, 1)
    },
    //图片开始上传
    imageBeforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: '加载中......',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    //图片上传成功
    imageUploadSuccess(response, file) {
      if (this.loading != undefined) {
        this.loading.close()
      }
      let imageList = this.imageList
      let item = response.data
      imageList.push(item)
      this.imageList = imageList
    },
    insertImage() {
      let imageList = this.imageList
      let imageHtml = ''
      this.imageList.forEach(val => {
        imageHtml = imageHtml + '<img width="100%" height="100%" src="' + val.url + '"/>'
      })
      if (imageHtml != '') {
        this.editorHandler.execCommand('inserthtml', imageHtml)
      }
      this.fileList = []
      this.dialogVisible = false
    },
    addCustomButtom(editorId) {
      let _this = this
      window.UE.registerUI(
        'test-button',
        function(editor, uiName) {
          // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
          editor.registerCommand(uiName, {
            execCommand: () => {
              _this.imageList = []
              _this.dialogVisible = true
              _this.editorHandler = editor
              //editor.execCommand('inserthtml', `<span>这是一段由自定义按钮添加的文字</span>`)
            }
          })

          // 创建一个 button
          var btn = new window.UE.ui.Button({
            // 按钮的名字
            name: uiName,
            // 提示
            title: '鼠标悬停时的提示文字',
            // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
            cssRules: 'background-position: -380px 0;',
            // 点击时执行的命令
            onclick: function() {
              // 这里可以不用执行命令，做你自己的操作也可
              editor.execCommand(uiName)
            }
          })

          // 当点到编辑内容上时，按钮要做的状态反射
          editor.addListener('selectionchange', function() {
            var state = editor.queryCommandState(uiName)
            if (state === -1) {
              btn.setDisabled(true)
              btn.setChecked(false)
            } else {
              btn.setDisabled(false)
              btn.setChecked(state)
            }
          })

          // 因为你是添加 button，所以需要返回这个 button
          return btn
        },
        47 /* 指定添加到工具栏上的哪个位置，默认时追加到最后 */,
        editorId /* 指定这个 UI 是哪个编辑器实例上的，默认是页面上所有的编辑器都会添加这个按钮 */
      )
    },
    beforeUpload(file) {
      this.fileParams = file
      this.uploadING = false
      let _this = this
      if (_this.fileParams) {
        const isJpgOrPng =
          _this.fileParams.type === 'image/jpeg' ||
          _this.fileParams.type === 'image/png' ||
          _this.fileParams.type === 'image/svg' ||
          _this.fileParams.type === 'image/jpg' ||
          _this.fileParams.type === 'image/gif'
        const isLt2M = _this.fileParams.size / 1024 / 1024 < 4
        if (!isJpgOrPng) {
          _this.$message.error('请上传jpg/png格式的图片!')
          return
        } else if (!isLt2M) {
          _this.$message.error('图片太大了，请上传4M以内的图片!')
          return
        } else {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          let formData = new FormData()
          formData.append('file', _this.fileParams)
          // formData.append('school_id', _this.$store.state.user.school)
          uploadPic(formData)
            .then(res => {
              _this.$message.success('上传成功')
              _this.imageList.push({ url: res.url })
              this.uploadING = true
            })
            .catch(err => {
              this.uploadING = true
              _this.$message.error('上传失败')
            })
        }
      } else {
        _this.$message.error('还没选择任何图片噢!')
        return
      }
      // 转化为blob
      return false
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    cancel() {
      this.dialogVisible = false
    }
  },
  watch: {
    value(newValue) {
      this.content = newValue
    },
    content(newValue) {
      this.$emit('input', newValue)
    }
  }
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.edui-default {
  line-height: 20px !important;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
<style scoped>
.image-upload-panel {
  overflow: hidden;
}
.image-upload-btn {
  float: left;
  width: 150px;
  height: 150px;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  line-height: 150px;
  text-align: center;
}

.image-upload-btn div {
  width: 150px;
}

.image-upload-btn i {
  font-size: 30px;
  font-weight: 400;
}
.image-item {
  float: left;
  width: 150px;
  height: 150px;
  background: #ddd;
  margin-right: 10px;
  border-radius: 6px;
  position: relative;
}
.image-item img {
  max-width: 150px;
  border-radius: 6px;
}
.image-del {
  position: absolute;
  top: 0px;
  right: 0px;
  color: red;
  font-weight: bold;
  font-size: 20px;
  cursor: pointer;
}
</style>